import 'package:bruno/bruno.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';

import '../../api/UserApi.dart';
import '../../api/dio/BaseModel.dart';
import '../../api/dio/DioClient.dart';
import '../../commponets/ItemView.dart';
import '../../home/AppLocale.dart';
import '../../routers/fluro_navigator.dart';
import '../../tools/widgets/CustomTopInputDialog.dart';
import '../../tools/widgets/my_app_bar.dart';
import '../../utils/toast_utils.dart';
import '../login/login_router.dart';
import 'model/UserModel.dart';


class UserInfoPage extends StatefulWidget {
  const UserInfoPage({
    super.key,
    this.userId,
    this.userModel,
    this.heroTag,
    this.goodsImageUrl
  });

  final int? userId;
  final UserModel? userModel;
  final String? goodsImageUrl;
  final String? heroTag;

  @override
  State<UserInfoPage> createState() => _UserInfoPageState();
}

class _UserInfoPageState extends State<UserInfoPage> {
  final UserApi _userApi = UserApi();
  late int _userId;
  UserModel? _userModel;
  final ImagePicker _picker = ImagePicker();

  @override
  void initState() {
    super.initState();
    _userId = widget.userId!;
    _userModel = widget.userModel!;
  }

  // 显示选择图片来源的对话框
  void _showImageSourceDialog() {


    List<BrnCommonActionSheetItem> actions = [];
    actions.add(BrnCommonActionSheetItem(
      '拍照',
      actionStyle: BrnCommonActionSheetItemStyle.normal,
    ));
    actions.add(BrnCommonActionSheetItem(
      '从相册选择',
      actionStyle: BrnCommonActionSheetItemStyle.normal,
    ));

    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.transparent,
      builder: (BuildContext context) {
        return BrnCommonActionSheet(
          actions: actions,
          clickCallBack: (
              int index,
              BrnCommonActionSheetItem actionEle,
              ) {
            // String title = actionEle.title;
            // BrnToast.show("title: $title, index: $index", context);
            if(index == 0){
              _pickImage(ImageSource.camera);
            }else{
              _pickImage(ImageSource.gallery);
            }
          },
        );
      }
    );
  }




  // 选择图片
  Future<void> _pickImage(ImageSource source) async {
    try {
      final XFile? image = await _picker.pickImage(
        source: source,
        imageQuality: 80, // 图片质量
        maxWidth: 800,    // 最大宽度
      );

      if (image != null) {
        // 选择图片后调用上传接口
        await _uploadAvatar(File(image.path));
      }
    } catch (e) {
      BrnToast.show('选择图片失败: ${e.toString()}', context);
    }
  }

  // 上传头像到服务器
  Future<void> _uploadAvatar(File imageFile) async {
    try {
      BrnLoadingDialog.show(context);

      // 调用上传接口
      final response = await _userApi.avatar(imageFile);

      BrnLoadingDialog.dismiss(context);

      if (response.code == 200) {
        // 上传成功，更新头像显示
        setState(() {
          _userModel?.avatar = response.data;
        });
        BrnToast.show('头像更新成功', context);
      } else {
        BrnToast.show(response.msg ?? '上传失败', context);
      }
    } catch (e) {
      BrnLoadingDialog.dismiss(context);
      BrnToast.show('上传出错: ${e.toString()}', context);
    }
  }



  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppBar(
        centerTitle: AppLocale.text('my_zhanhaoshezhi'),
        backgroundColor: Colors.transparent,
        dropdownWidth: 140,
        dropdownBackgroundColor: Colors.white,
        dropdownBorderRadius: 20,
      ),
      body: Container(
          child: Column(
            children: [
              const SizedBox(height: 20,),
              ItemView(
                width: 400,
                height: 50,
                leftPadding: 10,
                rightPadding: 20,
                leftWidget: Row(
                  children: [
                    const SizedBox(width: 10),
                    Text(
                      AppLocale.text('my_touxiang'),
                      style: TextStyle(
                          fontSize: 15.0,
                          color: Colors.black
                      ),
                    ),
                  ],
                ),
                rightWidget: Row(
                  children: [
                    Row(
                      children: [
                        CircleAvatar(
                          radius: 15,
                          backgroundColor: Colors.grey[200],
                          child: ClipOval(
                            child: Image.network(
                              _userModel?.avatar?.isNotEmpty == true
                                  ? '${DioClient.baseUrl}${_userModel!.avatar}'
                                  : 'http://43.139.39.5:82/pho/face/default.jpg',
                              width: 30,
                              height: 30,
                              fit: BoxFit.cover,
                            ),
                          ),
                        ),
                        const SizedBox(width: 5,),
                        const Icon(
                          Icons.arrow_forward_ios,
                          color: Colors.grey,
                          size: 14,
                        ),
                        const SizedBox(width: 5),
                      ],
                    )
                  ],
                ),
                borderRadius: 8,
                onTap: () {
                  // 点击头像时显示选择对话框
                  _showImageSourceDialog();
                },
              ),

              ItemView(
                width: 400,
                height: 50,
                leftPadding: 10,
                rightPadding: 20,
                leftWidget: Row(
                  children: [
                    const SizedBox(width: 10),
                    Text(
                      AppLocale.text('my_nicheng'),
                      style: TextStyle(
                          fontSize: 15.0,
                          color: Colors.black
                      ),
                    ),
                  ],
                ),
                rightWidget: Row(
                  children: [
                    Text(
                      _userModel?.userName ?? '',
                      style: TextStyle(
                          fontSize: 14.0,
                          color: Colors.black54
                      ),
                    ),
                    const SizedBox(width: 5,),
                    const Icon(
                      Icons.arrow_forward_ios,
                      color: Colors.grey,
                      size: 14,
                    ),
                    const SizedBox(width: 5),
                  ],
                ),
                borderRadius: 8,
                  // 在昵称Item的onTap中调用
                  onTap: () {
                    CustomTopInputDialog.show(
                      context,
                      title: AppLocale.text('my_xiugainicheng'),
                      hintText: _userModel?.userName ?? "",
                      message: AppLocale.text('my_xiugainichengdata'),
                      confirmText: AppLocale.text('confirm'),
                      cancelText: AppLocale.text('cancel'),
                      // 可自定义按钮样式
                      // buttonWidth: 90,
                      // buttonHeight: 45,
                      // confirmButtonColor: Colors.blue,
                      // 确定回调
                      onConfirm: (newNickname) async {

                        final toUpdate = {
                          "userId": _userId,
                          "userName": newNickname,
                          "phonenumber": null,
                        };

                        final response = await _userApi.updateUserData(toUpdate);
                        if (response.code == 200) {
                          // 调用更新昵称接口
                          setState(() {
                            _userModel?.userName = newNickname;
                          });
                          Toast.show(AppLocale.text('my_xiugainichengchenggong'));
                        }else{
                          Toast.show(response.msg ?? AppLocale.text('my_xiugainichengshibai'));
                        }
                      },
                    );
                  }
              ),

              const SizedBox(height: 20,),


              // ItemView(
              //   width: 400,
              //   height: 50,
              //   leftPadding: 10,
              //   rightPadding: 20,
              //   leftWidget: Row(
              //     children: [
              //       const SizedBox(width: 10),
              //       const Text(
              //         "地区",
              //         style: TextStyle(
              //             fontSize: 15.0,
              //             color: Colors.black
              //         ),
              //       ),
              //     ],
              //   ),
              //   rightWidget: Row(
              //     children: [
              //       Text(
              //         _userModel?.createBy ?? '',
              //         style: TextStyle(
              //             fontSize: 14.0,
              //             color: Colors.black54
              //         ),
              //       ),
              //       const SizedBox(width: 5,),
              //       const Icon(
              //         Icons.arrow_forward_ios,
              //         color: Colors.grey,
              //         size: 14,
              //       ),
              //       const SizedBox(width: 5),
              //     ],
              //   ),
              //   borderRadius: 8,
              //   onTap: () {
              //
              //   },
              // ),

              ItemView(
                width: 400,
                height: 50,
                leftPadding: 10,
                rightPadding: 20,
                leftWidget: Row(
                  children: [
                    const SizedBox(width: 10),
                    Text(
                      AppLocale.text('my_shoujihao'),
                      style: TextStyle(
                          fontSize: 15.0,
                          color: Colors.black
                      ),
                    ),
                  ],
                ),
                rightWidget: Row(
                  children: [
                    Text(
                      _userModel?.phonenumber ?? AppLocale.text('my_qubangding'),
                      style: TextStyle(
                          fontSize: 14.0,
                          color: Colors.black54
                      ),
                    ),
                    const SizedBox(width: 5,),
                    const Icon(
                      Icons.arrow_forward_ios,
                      color: Colors.grey,
                      size: 14,
                    ),
                    const SizedBox(width: 5),
                  ],
                ),
                borderRadius: 8,
                onTap: () {

                  // CustomTopInputDialog.show(
                  //   context,
                  //   title: "修改手机号",
                  //   hintText: _userModel?.userName ?? "",
                  //   message: "最多输入20个字符，支持中英文、数字",
                  //   confirmText: "确定",
                  //   cancelText: "取消",
                  //   // 可自定义按钮样式
                  //   // buttonWidth: 90,
                  //   // buttonHeight: 45,
                  //   // confirmButtonColor: Colors.blue,
                  //   // 确定回调
                  //   onConfirm: (newNickname) async {
                  //
                  //     final toUpdate = {
                  //       "userId": _userId,
                  //       "userName": newNickname,
                  //       "phonenumber": null,
                  //     };
                  //
                  //     final response = await _userApi.updateUserData(toUpdate);
                  //     if (response.code == 200) {
                  //       // 调用更新昵称接口
                  //       setState(() {
                  //         _userModel?.userName = newNickname;
                  //       });
                  //       Toast.show("昵称修改成功");
                  //     }else{
                  //       Toast.show(response.msg ?? "昵称修改失败");
                  //     }
                  //   },
                  // );

                },
              ),


              ItemView(
                width: 400,
                height: 50,
                leftPadding: 10,
                rightPadding: 20,
                leftWidget: Row(
                  children: [
                    const SizedBox(width: 10),
                    Text(
                      AppLocale.text('my_youxiang'),
                      style: TextStyle(
                          fontSize: 15.0,
                          color: Colors.black
                      ),
                    ),
                  ],
                ),
                rightWidget: Row(
                  children: [
                    Text(
                      _userModel?.email ?? AppLocale.text('my_qubangding'),
                      style: TextStyle(
                          fontSize: 14.0,
                          color: Colors.black54
                      ),
                    ),
                    const SizedBox(width: 5,),
                    const Icon(
                      Icons.arrow_forward_ios,
                      color: Colors.grey,
                      size: 14,
                    ),
                    const SizedBox(width: 5),
                  ],
                ),
                borderRadius: 8,
                onTap: () {


                  CustomTopInputDialog.show(
                    context,
                    title: AppLocale.text('my_xiugaiyouxiang'),
                    hintText: _userModel?.email ?? "",
                    message: AppLocale.text('my_xiugaiyouxiangdata'),
                    confirmText: AppLocale.text('cancel'),
                    cancelText: AppLocale.text('submit'),
                    isFu: true,
                    onConfirm: (email) async {
                      final toUpdate = {
                        "userId": _userId,
                        "email": email,
                        "phonenumber": null,
                      };

                      final response = await _userApi.updateUserData(toUpdate);
                      if (response.code == 200) {
                        // 调用更新昵称接口
                        setState(() {
                          _userModel?.email = email;
                        });
                        Toast.show(AppLocale.text('my_xiugaiyouxiangchenggong'));
                      }else{
                        Toast.show(response.msg ?? AppLocale.text('my_xiugaiyouxiangshibai'));
                      }
                    },
                  );

                },
              ),


              ItemView(
                width: 400,
                height: 50,
                leftPadding: 10,
                rightPadding: 20,
                leftWidget: Row(
                  children: [
                    const SizedBox(width: 10),
                    Text(
                      AppLocale.text('my_denglumimaxiugai'),
                      style: TextStyle(
                          fontSize: 15.0,
                          color: Colors.black
                      ),
                    ),
                  ],
                ),
                borderRadius: 8,
                onTap: () {

                  NavigatorUtils.push(
                      context, LoginRouter.resetPasswordPage
                  );

                },
              ),




              const SizedBox(height: 20,),


              ItemView(
                width: 400,
                height: 50,
                leftPadding: 10,
                rightPadding: 20,
                leftWidget: Row(
                  children: [
                    const SizedBox(width: 10),
                    Text(
                      AppLocale.text('my_zhuxiaozhanghao'),
                      style: TextStyle(
                          fontSize: 15.0,
                          color: Colors.black
                      ),
                    ),
                  ],
                ),
                borderRadius: 8,
                onTap: () {

                },
              ),

            ],
          )
      ),
    );
  }
}
